package org.hefan.hrm.exception;

import org.hefan.hrm.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 解决controller中的大量 try catch
 */
@RestControllerAdvice //在controller前后执行逻辑，底层是aop
public class AllExceptionHandler {

    //捕获全局异常
    @ExceptionHandler(GlobalException.class)
    public AjaxResult globalExceptionHandle(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setErrorCode(e.getErrorCode()).setMessage(e.getMessage());
    }

    //捕获jsr303参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult exceptionHandle(MethodArgumentNotValidException e){
        e.printStackTrace();
        //获取所有字段错误
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        //遍历所有字段错误进行拼接
        StringBuilder message = new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            message.append(fieldError.getDefaultMessage()+",");
        });
        //去除最后一个逗号
        String str = message.toString();
        str = str.substring(0,str.length()-1);
        return AjaxResult.me().setSuccess(false)
                .setErrorCode(ErrorCode.CODE_400_PARAM_VALID.getCode())
                .setMessage(str);
    }

    //捕获系统异常
//    @ExceptionHandler(AccessDeniedException.class)
//    public AjaxResult exceptionHandle(AccessDeniedException e){
//        return AjaxResult.me().setSuccess(false)
//                .setErrorCode(403)
//                .setMessage("您没有权限访问！请联系管理员！");
//    }
    //捕获系统异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandle(Exception e){
        String clsName = e.getClass().getName();
        if (clsName.contains("AccessDeniedException")){
            return AjaxResult.me().setSuccess(false)
                    .setErrorCode(403)
                    .setMessage("您没有权限访问！请联系管理员！");
        }
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setErrorCode(ErrorCode.CODE_500_SYSTEM_ERROR.getCode())
                .setMessage(ErrorCode.CODE_500_SYSTEM_ERROR.getMessage());
    }
}
